package org.groovymud.shell.security.loginsteps;

import static org.groovymud.shell.security.loginsteps.CallBackDelegate.createCallbackArray;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.ConfirmationCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;

import org.groovymud.object.alive.Player;
import org.groovymud.object.registry.Registry;
import org.groovymud.shell.security.MudLoginModuleData;
import org.groovymud.shell.security.callbacks.SelfHandlingConfirmationCallback;

public class CheckDuplicatePlayer extends LoginStep {

    private final Registry registry;

    public CheckDuplicatePlayer(Registry registry) {
        this.registry = registry;
    }

    @Override
	public void execute(MudLoginModuleData data) throws IOException, UnsupportedCallbackException, FailedLoginException {
		Callback[] cb;
		Player dupe = data.getDupe();
		if (dupe != null) {
			ConfirmationCallback alreadyPlaying = new SelfHandlingConfirmationCallback("You are already playing. Throw the other copy out?", ConfirmationCallback.INFORMATION, ConfirmationCallback.YES_NO_OPTION, ConfirmationCallback.NO);
			cb = createCallbackArray(alreadyPlaying);
			data.getCallbackHandler().handle(cb);
			if (alreadyPlaying.getSelectedIndex() == ConfirmationCallback.YES) {
				registry.dest(dupe, true);
			} else {
				throw new FailedLoginException("cannot log in, already logged in!");
			}

		}
		if (getNextStep() != null) {
			getNextStep().execute(data);
		}
	}
}
